package com.xuyiwei.mayi;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xuyiwei on 2019/4/16.
 */
public class ServletDemo extends HttpServlet {
    private int i = 1;

    public ServletDemo() {
        System.out.println("servlet构造方法");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println(getServletContext().getInitParameter("webParam"));

        //这个是获得web下面的文件 而不是获得resource下面的
//        InputStream in = getServletContext().getResourceAsStream("a.txt");
//        byte[] bytes = new byte[1024];
//        int len = -1;
//        while ((len= in.read(bytes))!=-1){
//            System.out.println(new String(bytes,0,len));
//        }

        //获得工程名称
        System.out.println("getServletContext().getContextPath():"+getServletContext().getContextPath());
        System.out.println("req.getServerName():"+req.getServerName());
        System.out.println("req.getScheme():"+req.getScheme());
        System.out.println("req.getServerPort():"+req.getServerPort());
        //getServletContext().getContextPath():/servletdemo
        //req.getServerName():192.168.1.113
        //req.getScheme():http
        //req.getServerPort():8080

        // 设置编码格式
        // resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");// 内容编码，防止出现中文乱码
        resp.setContentType("text/html;charset=utf-8");
        synchronized (ServletDemo.class) {
            // 向浏览器输出内容
            resp.getWriter().write("这是第" + i + "次访问...");
            try {
            } catch (Exception e) {
                // TODO: handle exception
            }

            i++;
        }

        Cookie cookie = new Cookie("servletdemo","servletdemo");
        cookie.setMaxAge(10);
        cookie.setDomain(".itxyw.com");
        cookie.setPath("/");
        resp.addCookie(cookie);
    }

    @Override
    public void destroy() {
        System.out.println("servlet已经被销毁");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("servlet的init方法");
    }
}
